import { clearScanRes } from "@/utils";
import { broadcastScan } from "./scan";

const TIME_OUT = 4 * 1000;

const useScan = ({ scanCallback, timeOutCallback, immediate = true }) => {
	// 报错定时器
	const timer = ref();
	// 清理定时器
	const clearTimer = () => {
		console.log(timer.value);

		if (!timer.value) {
			return;
		}
		clearInterval(timer.value);
		timer.value = null;
	};

	const isRes = ref(false);

	const scanLoading = ref(false);

	// 实体键是否正处于按下的状态
	const isBtnKeyDown = ref<boolean>(false);

	// 扫描结果处理
	const innerScanCallback = (res) => {
		console.log("扫描结果：", res);
		scanLoading.value = false;
		isRes.value = true;
		scanCallback(res);
	};

	// 监听按下扫描实体键
	const listenScanBtnKeyDown = (event) => {
		if (event.keyCode !== 142) {
			return;
		}

		scanLoading.value = true;

		if (isBtnKeyDown.value) {
			console.log("按键已被按下");
			return;
		}

		isBtnKeyDown.value = true;
		clearTimer();
		console.log("start keydown");

		// 超时报错事件只在实体键按下的时候才生效
		timer.value = setInterval(() => {
			if (isBtnKeyDown.value) {
				console.log("start over", isRes.value);

				if (!isRes.value) {
					console.log("error");
					scanLoading.value = false;
					timeOutCallback();
				}
			}
		}, TIME_OUT);
	};

	const listenScanBtnKeyUp = (event) => {
		console.log(event.keyCode, "end keyup");

		if (event.keyCode !== 142) {
			return;
		}
		scanLoading.value = false;
		isBtnKeyDown.value = false;
		clearTimer();
	};

	// 注销扫描 退出页面 隐藏pda时使用
	const cancelScanPage = () => {
		broadcastScan.stop();

		/* #ifdef APP-PLUS */
		plus.key.removeEventListener("keydown", listenScanBtnKeyDown);
		plus.key.removeEventListener("keyup", listenScanBtnKeyUp);

		/* #endif */

		clearTimer();
	};

	// 手动开启扫描
	// 超时逻辑和实体键按下扫描一样  区别在于超时一次后就会停止
	const startScan = () => {
		console.log("startScan");
		/* #ifdef APP-PLUS */
		broadcastScan.triggerScan();
		if (isBtnKeyDown.value) {
			console.log("正在扫描中");
			return;
		}
		isBtnKeyDown.value = true;
		clearTimer();
		console.log("start keydown");

		// 超时报错事件只在实体键按下的时候才生效
		timer.value = setInterval(() => {
			if (!isRes.value) {
				console.log("error");
				timeOutCallback();

				isBtnKeyDown.value = false;
				clearTimer();
			}
		}, TIME_OUT);

		/* #endif */
	};

	onLoad(() => {
		broadcastScan.init(innerScanCallback);

		/* #ifdef APP-PLUS */
		plus.key.addEventListener("keydown", listenScanBtnKeyDown);
		plus.key.addEventListener("keyup", listenScanBtnKeyUp);

		/* #endif */
	});

	onShow(() => {
		immediate && broadcastScan.start();
	});

	onHide(() => {
		cancelScanPage();
	});

	onUnload(() => {
		cancelScanPage();
	});

	return {
		loading: scanLoading,
		cancelScan: cancelScanPage,
		// startScan: startScan,
	};
};

export default useScan;
